﻿using System;
using System.Runtime.InteropServices;
using Microsoft.Xna.Framework;

namespace Tiny.Imaging.Filter.MathLibrary
{
    public struct MathLibrary
    {
        public static float Sqrt(float z)
        {
            if (z == 0) return 0;
            FloatIntUnion u;
            u.tmp = 0;
            u.f = z;
            u.tmp -= 1 << 23;
            u.tmp >>= 1;
            u.tmp += 1 << 29;
            return u.f;
        }

        public static double Pow(double a, double b)
        {
            var tmp = (int) (BitConverter.DoubleToInt64Bits(a) >> 32);
            var tmp2 = (int) (b*(tmp - 1072632447) + 1072632447);
            return BitConverter.Int64BitsToDouble(((long) tmp2) << 32);
        }

        public static int Clamp(int pixel)
        {
            return Math.Max(0, Math.Min(pixel, 255));
        }

        public static int Clamp(float pixel)
        {
            return (int) MathHelper.Clamp(pixel, 0, 255);
        }

        #region Nested type: FloatIntUnion

        [StructLayout(LayoutKind.Explicit)]
        private struct FloatIntUnion
        {
            [FieldOffset(0)] public float f;

            [FieldOffset(0)] public int tmp;
        }

        #endregion
    }
}